package com.sky.yipinyoufujava.controller;

import com.sky.yipinyoufujava.pojo.*;
import com.sky.yipinyoufujava.pojo.from.GetSingleOrderGoodsFrom;
import com.sky.yipinyoufujava.pojo.from.OrderForm;
import com.sky.yipinyoufujava.pojo.goods.*;
import com.sky.yipinyoufujava.pojo.order.CreateOrder;
import com.sky.yipinyoufujava.pojo.order.Order;
import com.sky.yipinyoufujava.pojo.order.OrderAddress;
import com.sky.yipinyoufujava.pojo.order.OrderStatus;
import com.sky.yipinyoufujava.result.Result;
import com.sky.yipinyoufujava.service.AddressService;
import com.sky.yipinyoufujava.service.GoodsService;
import com.sky.yipinyoufujava.service.LoginService;
import com.sky.yipinyoufujava.service.OrderService;
import com.sky.yipinyoufujava.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private LoginService loginService;
    @Autowired
    private GoodsService goodsService;
    @PostMapping("/getOrder")
    private Result getOrder(@RequestBody OrderForm orderForm){
        log.info("获取订单列表,{}",orderForm);
        // 定义日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            // 检查日期字符串是否为null或空，如果不是，则进行日期格式转换
            String startTimeStr = orderForm.getOrderStartTime();
            String endTimeStr = orderForm.getOrderEndTime();
            if (startTimeStr != null && !startTimeStr.isEmpty()) {
                Date startTime = dateFormat.parse(startTimeStr + " 00:00:00");
                orderForm.setOrderStartTime(dateFormat.format(startTime));
            }
            if (endTimeStr != null && !endTimeStr.isEmpty()) {
                Date endTime = dateFormat.parse(endTimeStr + " 23:59:59");
                orderForm.setOrderEndTime(dateFormat.format(endTime));
            }
        } catch (Exception e) {
            log.error("日期格式转换失败", e);
            return Result.error("日期格式转换失败");
        }

        // 使用转换后的OrderForm对象获取订单列表
        List<Order> orderList = orderService.getOrder(orderForm);
        log.info("获取的列表，{}", orderList);

        return Result.success(orderList);
    };


//    获取订单状态列表

    
    /**
     * 获取单个订单的详情信息
     * @param orderId
     * @return
     */
    @PostMapping("/getSingleOrderInfo")
    private Result getSingleOrderInfo(@RequestBody GetSingleOrderGoodsFrom orderId){
        log.info("订单id,{}",orderId.getOrderId());
        Order goodsList = orderService.getSingleOrderInfo(orderId);
        log.info("订单信息,{}",goodsList);

        OrderAddress addressList = addressService.getOrderAddress(orderId);
        goodsList.setShippingAddress(addressList);
        List<Goods> orderGoodsList = orderService.getSingleOrderGoods(orderId);
        // 获取店铺信息
        for (Goods goods : orderGoodsList) {
            log.info("循环的结果，{}",goods.getId());
            goods.setGoodsShops(goodsService.getGoodsShops(goods.getGoodsId()));
        };
        goodsList.setOrderGoodsContent(orderGoodsList);
        return Result.success(goodsList);
    }

    /**
     * 单独获取 某个订单商品
     */
    @PostMapping("/getSingleOrderGoods")
    private Result getSingleOrderGoods(@RequestBody GetSingleOrderGoodsFrom orderId){
        log.info("订单id,{}",orderId.getOrderId());
         List<Goods> goodsLists = orderService.getSingleOrderGoods(orderId);

        return Result.success(goodsLists);
    }


    /**
     * 创建临时订单
     */
    @PostMapping("/createTemporaryOrder")
    private Result createTemporaryOrder(@RequestBody CreateOrder createOrder){
        log.info("创建临时订单,{}",createOrder);
//        生成订单号
        String orderNumber = createOrder();
        createOrder.setOrderId(orderNumber);
        // 创建临时订单
        // orderService.createTemporaryOrder(createOrder);
        return Result.success(orderNumber);
    }
    /**
     * 创建正式订单
     */
    @PostMapping("/createOfficiallyOrder")
    private Result createOfficiallyOrder(@RequestBody Order order, @RequestHeader("Token") String token){
        log.info("创建正式订单,{}",order);
        Map<String, Object> stringObjectMap = JwtUtil.parseToken(token);
        Object UserId = stringObjectMap.get("id");
        User userInfo = loginService.queryUserId(UserId);
        log.info("创建的用户信息,{}",userInfo);

        String orderNumber = createOrder();
        order.setOrderId(orderNumber);
        order.setOrderUserId(userInfo.getId());
        order.setOrderUser(userInfo.getUsername());
        log.info("创建正式订单,{}",order);
        orderService.createOfficiallyOrder(order);
        orderService.insertOrderGoodsList(orderNumber,order.getOrderGoodsId());
//        少一个插入 订单地址的
        return Result.success(orderNumber);
    }


//    生成订单号
        private String createOrder() {
            // 生成订单号格式：2024102300001
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            String datePrefix = dateFormat.format(new Date());
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String orderIdKey = "orderIdCounter:" + datePrefix; // 使用日期作为键的一部分
            // 获取并递增订单号计数器
            Long orderIdCounter = operations.increment(orderIdKey);
            // 如果是当天的第一个订单，设置过期时间为24小时
            if (orderIdCounter == 1L) {
                operations.set(orderIdKey, "1", 24, TimeUnit.HOURS);
                // 构建订单号
                String orderId = datePrefix + "0001";
                // 这里将 orderId 设置到相应的变量或返回值中
                return orderId; // 直接返回订单号
            }
            // 格式化订单号
            String orderNumber = datePrefix + String.format("%06d", orderIdCounter);
            log.info("订单号: {}", orderNumber);
            return orderNumber; // 返回格式化后的订单号
        };


    /**
     * 修改订单状态
     * 订单状态（例如：1 = 待支付、2 = 已支付、3 = 已发货、4 = 已结单、5 = 待评价、6 = 待接单、7 = 已接单、9 = 已取消）
     */

    @PostMapping("/updateOrderStatus")
    private Result updateOrderStatus(@RequestBody OrderStatus orderStatus){
        log.info("修改订单状态,{}",orderStatus);
        orderService.updateOrderStatus(orderStatus);
        return Result.success("修改成功！");
    };


    /**
     * 更新订单新信息
     */

    @PostMapping("/updateOrderInfo")
    private Result updateOrderInfo(@RequestBody Order order){
       log.info("更新订单信息,{}",order);
       orderService.updateOrderInfo(order);
       return Result.success("更新成功！");
    }
}
